package com.yzx.yunyanzhengdemo.activity;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.bean.Person;
import com.btl.cygf.R;
import com.btl.http.HttpServies;
import com.btl.utils.MD5Encrypt;
import com.verificationcodelib.api.VerificationCode;
import com.verificationcodelib.listener.UcsReason;
import com.verificationcodelib.listener.VerificationCodeListener;
import com.yzx.yunyanzhengdemo.util.HttpConnect;

public class RegisterActivity extends Activity implements OnClickListener {

	private LinearLayout Ldata_phonenum;
	private LinearLayout Ldata_setinfo;
	private LinearLayout Ldata_registerinfo;
	private LinearLayout Ldata_check;
	private LinearLayout Ldata_verificate;
	private ImageView L_back;
	private Button bt_data_next;
	private Button bt_time_send;
	private TextView phonenumber;
	private TextView tv_data_title;
	private TextView tv_thanks;
	private TextView tv_docs;
	private TextView tv_admininfo;
	private TextView tv_passwardinfo;
	private EditText et_data_phonenum;
	private TextView et_data_admin;
	private EditText et_data_passward;
	private EditText et_data_verification;
	private CheckBox cb_next;
	private int numpage = 1;
	private String phonenum;
	private String sign;
	private Boolean vfc = true;
	private Boolean vfc_result = false;
	private Timer timer = null;
	String type;

	boolean value = false;
	String result;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x1123) {

				if (value) {
					if (type.equals("1")) {
						setFinishLayout();
						Toast.makeText(getApplicationContext(), "注册成功!", 1)
								.show();

					} else {
						Toast.makeText(getApplicationContext(), "密码修改成功", 1)
						.show();
						startActivity(new Intent(RegisterActivity.this,
								LoginActivity.class));
					}
				} else {
					if (type.equals("1")) {

						Toast.makeText(getApplicationContext(), "注册失败!", 1)
								.show();
					}
					
					
					Intent it = new Intent(RegisterActivity.this,
							LoginActivity.class);
					it.putExtra("type", "2");
					startActivity(it);

				}

			}

			if (msg.what == 0x1124) {
				if (type.equals("1")) {
					if (et_data_phonenum.getText().toString().length() == 11
							&& result.equals("未注册")) {
						RequestVerificationCode();
					} else if (et_data_phonenum.getText().toString().length() == 11
							&& result.equals("已注册")) {
						Toast.makeText(getApplicationContext(), "该号码已被注册！！", 1)
								.show();
					}

				} else {
					if (et_data_phonenum.getText().toString().length() == 11
							&& result.equals("未注册")) {
						Toast.makeText(getApplicationContext(), "该号码不存在！！", 1)
								.show();
					} else if (et_data_phonenum.getText().toString().length() == 11
							&& result.equals("已注册")) {
						tv_data_title.setText("忘记密码");
						RequestVerificationCode();
					}
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setNoTitle();
		setContentView(R.layout.register_activity);

		Intent it = getIntent();
		type = it.getStringExtra("type");

		initView();
		setListener();
	}

	// 无标题
	public void setNoTitle() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	private void initView() {
		// TODO Auto-generated method stub
		phonenumber = (TextView) findViewById(R.id.phonenum);
		Ldata_phonenum = (LinearLayout) findViewById(R.id.data_phonenum);
		Ldata_setinfo = (LinearLayout) findViewById(R.id.data_setinfo);
		Ldata_registerinfo = (LinearLayout) findViewById(R.id.data_registerinfo);
		Ldata_check = (LinearLayout) findViewById(R.id.data_check);
		Ldata_verificate = (LinearLayout) findViewById(R.id.phone_num_verificate);
		L_back = (ImageView) findViewById(R.id.l_back);

		bt_data_next = (Button) findViewById(R.id.bt_data_next);
		bt_time_send = (Button) findViewById(R.id.time_send);
		tv_data_title = (TextView) findViewById(R.id.date_title);
		tv_thanks = (TextView) findViewById(R.id.thanks_info);
		tv_admininfo = (TextView) findViewById(R.id.admin_info);
		tv_passwardinfo = (TextView) findViewById(R.id.passward_info);
		tv_docs = (TextView) findViewById(R.id.tv_docs);

		et_data_phonenum = (EditText) findViewById(R.id.phonenum);
		et_data_admin = (TextView) findViewById(R.id.admin);
		et_data_passward = (EditText) findViewById(R.id.passward);
		et_data_verification = (EditText) findViewById(R.id.verificate);

		cb_next = (CheckBox) findViewById(R.id.cb_next);

		if (type.equals("2")) {
			Ldata_check.setVisibility(View.GONE);
			tv_data_title.setText("忘记密码");

		}

		et_data_phonenum.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				String hint;
				if (hasFocus) {
					hint = et_data_phonenum.getHint().toString();
					et_data_phonenum.setTag(hint);
					et_data_phonenum.setHint("");

				} else {
					hint = et_data_phonenum.getTag().toString();
					et_data_phonenum.setHint(hint);

				}
			}

		});

		et_data_verification
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View arg0, boolean hasFocus) {
						String hint;
						if (hasFocus) {
							hint = et_data_phonenum.getHint().toString();
							et_data_verification.setTag(hint);
							et_data_verification.setHint("");
						} else {
							hint = et_data_verification.getTag().toString();
							et_data_verification.setHint(hint);
						}
					}

				});
	}

	private void setListener() {
		// TODO Auto-generated method stub
		bt_data_next.setOnClickListener(this);
		L_back.setOnClickListener(this);
		bt_time_send.setOnClickListener(this);
		bt_time_send.setClickable(false);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bt_data_next:// 下一步
			switch (numpage) {
			case 1:
				new Thread(new Runnable() {

					@Override
					public void run() {
						Map<String, String> params = new HashMap<>();
						params.put("phone", et_data_phonenum.getText()
								.toString());

						try {

							result = (String) HttpServies.SendPostRequest(
									getResources().getString(R.string.url)
											+ "/CYGF/verification.user",
									params, "utf-8", 2);

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						handler.sendEmptyMessage(0x1124);

					}
				}).start();

				break;
			case 2:

				StartVerificationCode();
				break;
			case 3:
				if (type.equals("1")) {

					if (et_data_passward.getText().toString().equals("")) {
							Toast.makeText(getApplicationContext(), "密码不能为空", 1).show();
							return;
					}

					new Thread(new Runnable() {
						@Override
						public void run() {

							Map<String, String> params = new HashMap<>();
							params.put("id", et_data_admin.getText().toString());
							params.put("pass", MD5Encrypt
									.getMD5Str(et_data_passward.getText()
											.toString()));

							try {
								value = (boolean) HttpServies.SendPostRequest(
										getResources().getString(R.string.url)
												+ "/CYGF/insert.user", params,
										"utf-8", 1);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							handler.sendEmptyMessage(0x1123);
						}
					}).start();
				} else {

					new Thread(new Runnable() {
						@Override
						public void run() {

							Map<String, String> params = new HashMap<>();
							params.put("id", et_data_admin.getText().toString());
							params.put("param", MD5Encrypt
									.getMD5Str(et_data_passward.getText()
											.toString()));
							params.put("type", "pass");

							try {
								value = (boolean) HttpServies.SendPostRequest(
										getResources().getString(R.string.url)
												+ "/CYGF/updatePerson.user",
										params, "utf-8", 1);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							handler.sendEmptyMessage(0x1123);
						}
					}).start();
				}

				break;
			case 4:
				numpage = 1;
				startActivity(new Intent(this, LoginActivity.class));
				break;
			default:
				break;
			}
			break;
		case R.id.l_back:// 返回
			switch (numpage) {
			case 1:
				startActivity(new Intent(this, LoginActivity.class));
				finish();
				break;
			case 2:
				numpage--;
				if (type.equals("1")) {

					tv_data_title.setText("注册（1/3）");
				} else {
					tv_data_title.setText("忘记密码");
				}
				Ldata_phonenum.setVisibility(View.VISIBLE);
				Ldata_setinfo.setVisibility(View.GONE);
				Ldata_verificate.setVisibility(View.GONE);
				break;
			case 3:
				numpage--;
				numpage--;
				if (type.equals("1")) {

					tv_data_title.setText("注册（1/3）");
				} else {
					tv_data_title.setText("忘记密码");
				}
				Ldata_phonenum.setVisibility(View.VISIBLE);
				Ldata_setinfo.setVisibility(View.GONE);
				Ldata_verificate.setVisibility(View.GONE);
				break;
			case 4:
				numpage--;
				tv_data_title.setText("注册（2/3）");

				bt_data_next.setBackgroundResource(R.drawable.btn_no);
				Ldata_setinfo.setVisibility(View.VISIBLE);
				Ldata_registerinfo.setVisibility(View.GONE);
				break;
			}
			break;
		case R.id.time_send:// 发用验证码
			numpage--;
			Resources resources = getBaseContext().getResources();
			bt_time_send.setBackgroundDrawable(resources
					.getDrawable(R.drawable.input_frame));
			bt_time_send.setClickable(false);
			RequestVerificationCode();
			break;
		}
	}

	/**
	 * 
	 * 请求验证码
	 * 
	 */
	private void RequestVerificationCode() {
		if (!cb_next.isChecked()) // 判断是否选中条款
			return;
		if (vfc) {
			vfc = false; // 防止多次点击
			numpage++;
			phonenum = et_data_phonenum.getText().toString();
			if (phonenum != null && phonenum.length() > 0) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						StringBuffer sbf = new StringBuffer();
						sbf.append("https://mid.ucpaas.com/vfs/demo/reg.do");
						// sbf.append("http://113.31.89.142:8091/vfs/demo/reg.do");
						sbf.append("?");
						sbf.append("phone=" + phonenum);
						try {
							JSONObject json = HttpConnect.doGet(sbf.toString());
							if (json.getInt("result") == 0) {
								sign = json.getString("sign");
								getVerificationCode(phonenum, sign);
							} else {
								vfc = true;
								switch (json.getInt("result")) {
								case 1:
									mRequestHandler.sendEmptyMessage(1);
									break;
								case 2:
									mRequestHandler.sendEmptyMessage(2);
									break;
								case 3:
									mRequestHandler.sendEmptyMessage(3);
									break;
								case 4:
									mRequestHandler.sendEmptyMessage(4);
									break;
								case 5:
									mRequestHandler.sendEmptyMessage(5);
									break;
								case 6:
									mRequestHandler.sendEmptyMessage(6);
									break;
								case 7:
									mRequestHandler.sendEmptyMessage(7);
									break;
								case 8:
									mRequestHandler.sendEmptyMessage(8);
									break;
								case 9:
									mRequestHandler.sendEmptyMessage(9);
									break;
								case 10:
									mRequestHandler.sendEmptyMessage(10);
									break;
								default:
									mRequestHandler.sendEmptyMessage(99);
									break;
								}
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
			}
		}
	}

	/**
	 * 
	 * 获得验证码
	 * 
	 */
	private void getVerificationCode(String phone, String sign) {
		VerificationCode.getVerificationCode(RegisterActivity.this, sign,
				"4c1990a5c1ad2674bc94bc39a6fd0699",
				"efb7e1de9da649fa83881afea2841cd7", "com.yzx.yunyanzhengdemo",
				60, 1, phone, new VerificationCodeListener() {

					@Override
					public void onVerificationCode(int arg0, UcsReason arg1) {
						vfc = true;
						if (arg1.getReason() == 300250) {
							Message msg = new Message();
							System.out.println("arg0:" + arg0);
							switch (arg0) {
							case 0:// 验证通过
								mUiHandler.sendEmptyMessage(2);
								break;
							case 1:// 以短信方式下发验证码
								vfc_result = true;
								mUiHandler.sendEmptyMessage(1);
								msg.obj = "短信";
								msg.what = 4;
								mUiHandler.sendMessage(msg);
								break;
							case 2:// 以语音方式下发验证码
								vfc_result = true;
								mUiHandler.sendEmptyMessage(1);
								msg.obj = "语言";
								msg.what = 4;
								mUiHandler.sendMessage(msg);
								break;
							}
						} else {
							numpage--;
							switch (arg1.getReason()) {
							case 300251:
								mRequestHandler.sendEmptyMessage(1);
								break;
							case 300252:
								mRequestHandler.sendEmptyMessage(2);
								break;
							case 300253:
								mRequestHandler.sendEmptyMessage(3);
								break;
							case 300254:
								mRequestHandler.sendEmptyMessage(4);
								break;
							case 300255:
								mRequestHandler.sendEmptyMessage(5);
								break;
							case 300256:
								mRequestHandler.sendEmptyMessage(6);
								break;
							case 300257:
								mRequestHandler.sendEmptyMessage(7);
								break;
							case 300258:
								mRequestHandler.sendEmptyMessage(8);
								break;
							case 300259:
								mRequestHandler.sendEmptyMessage(9);
								break;
							case 300260:
								mRequestHandler.sendEmptyMessage(10);
								break;
							default:
								mRequestHandler.sendEmptyMessage(99);
								break;
							}
						}
					}

				});
	}

	/**
	 * 
	 * 开始对验证码验证
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private void StartVerificationCode() {
		if (vfc_result) {
			// stopCallTimer();
			vfc_result = false;
			VerificationCode.doVerificationCode(RegisterActivity.this,
					phonenum, et_data_verification.getText().toString(),
					"4c1990a5c1ad2674bc94bc39a6fd0699",
					"efb7e1de9da649fa83881afea2841cd7",
					new VerificationCodeListener() {
						@Override
						public void onVerificationCode(int arg0, UcsReason arg1) {

							switch (arg1.getReason()) {
							case 300250:
								mRequestHandler.sendEmptyMessage(0);
								mUiHandler.sendEmptyMessage(2);
								break;
							case 300251:
								mRequestHandler.sendEmptyMessage(1);
								break;
							case 300252:
								mRequestHandler.sendEmptyMessage(2);
								break;
							case 300253:
								mRequestHandler.sendEmptyMessage(3);
								break;
							case 300254:
								mRequestHandler.sendEmptyMessage(4);
								break;
							case 300255:
								mRequestHandler.sendEmptyMessage(5);
								break;
							case 300256:
								mRequestHandler.sendEmptyMessage(6);
								break;
							case 300257:
								mRequestHandler.sendEmptyMessage(7);
								break;
							case 300258:
								mRequestHandler.sendEmptyMessage(8);
								break;
							case 300259:
								mRequestHandler.sendEmptyMessage(9);
								break;
							case 300260:
								mRequestHandler.sendEmptyMessage(10);
								break;
							default:
								mRequestHandler.sendEmptyMessage(99);
								break;
							}
							vfc_result = true;
						}
					});
		}
	}

	/**
	 * 
	 * 显示验证码下发方式
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private void setSendMethods(String Methods) {
		CharSequence str_docs = "本次验证码以" + Methods + "方式下发，请注意查收";
		SpannableStringBuilder style_docs = new SpannableStringBuilder(str_docs);
		style_docs.setSpan(new BackgroundColorSpan(0xff62b03d), 6, 8,
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_docs.setText(style_docs);
	}

	/**
	 * 
	 * 到第二步UI验证界面
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private void setSecondCodeLayout() {
		Ldata_verificate.setVisibility(View.VISIBLE);
		bt_data_next.setBackgroundResource(R.drawable.btn_no);
		startCallTimer();
	}

	/**
	 * 
	 * 到第二步UI输入用户名和密码界面
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private void setSecondInfoLayout() {
		numpage++;
		Ldata_check.setVisibility(View.GONE);
		Ldata_phonenum.setVisibility(View.GONE);

		Ldata_verificate.setVerticalGravity(View.GONE);
		Ldata_setinfo.setVisibility(View.VISIBLE);
		if (type.equals("1")) {
			tv_data_title.setText("注册（2/3）");
		} else {
			tv_data_title.setText("忘记密码");
		}

		et_data_admin.setText(phonenumber.getText().toString());
	}

	/**
	 * 
	 * 到最后一步UI界面
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private void setFinishLayout() {

		Person p = new Person();
		p.setPid(et_data_admin.getText().toString());
		p.setPpass(et_data_passward.getText().toString());
		numpage++;
		Ldata_setinfo.setVisibility(View.GONE);
		Ldata_registerinfo.setVisibility(View.VISIBLE);
		tv_data_title.setText("注册（3/3）");
		bt_data_next.setText("完成");
		bt_data_next.setBackgroundResource(R.drawable.btn_yes);
		tv_admininfo.setText("用户名：" + et_data_admin.getText().toString());
		tv_passwardinfo.setText("密    码："
				+ et_data_passward.getText().toString());
		CharSequence str_thanks = "感谢您的注册创意工坊，以下是您的注册信息，请妥善保存，谢谢。";
		SpannableStringBuilder style_thanks = new SpannableStringBuilder(
				str_thanks);
		style_thanks.setSpan(new BackgroundColorSpan(0xff62b03d), 5, 13,
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_thanks.setText(style_thanks);
		CharSequence str_admin = "用户名：" + et_data_admin.getText().toString();
		SpannableStringBuilder style_admin = new SpannableStringBuilder(
				str_admin);
		style_admin.setSpan(new BackgroundColorSpan(0xff62b03d), 4,
				str_admin.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_admininfo.setText(style_admin);
		CharSequence str_passward = "密    码："
				+ et_data_passward.getText().toString();
		SpannableStringBuilder style_passward = new SpannableStringBuilder(
				str_passward);
		style_passward.setSpan(new BackgroundColorSpan(0xff62b03d), 7,
				str_passward.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_passwardinfo.setText(style_passward);

	}

	/**
	 * 
	 * Http请求反馈提示
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private Handler mRequestHandler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			System.out.println("Message:" + msg.what);
			switch (msg.what) {
			case 0:
				Toast.makeText(RegisterActivity.this, "验证成功",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				Toast.makeText(RegisterActivity.this, "开发者账号无效",
						Toast.LENGTH_SHORT).show();
				break;
			case 2:
				Toast.makeText(RegisterActivity.this, "验证码错误",
						Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(RegisterActivity.this, "验证码过期",
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(RegisterActivity.this, "30秒内重复请求",
						Toast.LENGTH_SHORT).show();
				break;
			case 5:
				Toast.makeText(RegisterActivity.this, "签名错误",
						Toast.LENGTH_SHORT).show();
				break;
			case 6:
				Toast.makeText(RegisterActivity.this, "手机号码无效",
						Toast.LENGTH_SHORT).show();
				break;
			case 7:
				Toast.makeText(RegisterActivity.this, "已经注册过",
						Toast.LENGTH_SHORT).show();
				break;
			case 8:
				Toast.makeText(RegisterActivity.this, "未创建智能短信模板",
						Toast.LENGTH_SHORT).show();
				break;
			case 9:
				Toast.makeText(RegisterActivity.this,
						"短信模板有误，需要检查是否创建智能验证短信模板，模板审核、参数", Toast.LENGTH_SHORT)
						.show();
				break;
			case 10:
				Toast.makeText(RegisterActivity.this,
						"应用状态有误，需要检查应用是否审核通过、是否上线", Toast.LENGTH_SHORT).show();
				break;
			case 99:
				Toast.makeText(RegisterActivity.this, "请求失败",
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	/**
	 * 
	 * 1.打开验证码验证UI界面 2.打开填写用户名和密码界面 3.更新验证码剩余时间显示
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private Handler mUiHandler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			System.out.println("MessageUI:" + msg.what);
			switch (msg.what) {
			case 1:
				setSecondCodeLayout();
				break;
			case 2:
				setSecondInfoLayout();
				break;
			case 3:
				int sencond = 60 - (Integer) msg.obj;
				bt_time_send.setText(sencond + "秒后重新发送");
				if (sencond == 0) {
					bt_time_send.setText("重新获取验证码");
				}
				break;
			case 4:
				String sendMethods = (String) msg.obj;
				setSendMethods(sendMethods);
				break;
			case 5:
				bt_time_send.setBackgroundColor(0xff62b03d);
				break;
			}
		}
	};

	/**
	 * 
	 * 验证码定时器开启
	 * 
	 * @author: xiongjijian
	 * 
	 */
	private int sencond = 0;

	public void startCallTimer() {
		sencond = 0;
		stopCallTimer();
		if (timer == null) {
			timer = new Timer();
		}
		;

		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				sencond++;
				if (sencond >= 60) {
					numpage--;
					sencond = 60;
					vfc = true;
					stopCallTimer();
					mUiHandler.sendEmptyMessage(5);
					bt_time_send.setClickable(true);
				}
				Message message = new Message();
				message.what = 3;
				message.obj = sencond;
				mUiHandler.sendMessage(message);
			}
		}, 0, 1000);
	}

	/**
	 * 
	 * 验证码定时器关闭
	 * 
	 * @author: xiongjijian
	 * 
	 */
	public void stopCallTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}
}
